package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class MateActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    private final int MSG_DetailOver=9002;
    private final int MSG_ItemOver =9003;
    private final int MSG_ERRMSG = 9004;
    private final int MSG_SaveTrans=9005;
    private final int MSG_TypeOver =9006;
    private final int msgShowImage =9007;
    private final int msgGetImg =9008;
    private final int msgGetPOOver =9009;
    private final int msgGetCallListOver=9010;
    private final int MSG_SonDetailOver=9011;

    //全局变量
    LinearLayout mainLinerLayout;
    String PrBarcode="";
    private ProgressDialog waitDialog = null;

    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,SelDBH="";
    EditText edt_barcode,edt_checkReal,sonBarcode;
    Button btn_find;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_Size,txt_StyleSort,txt_ColorNo,txt_PSXX;
    GridView titleGrid,itemGrid;
    ListView detailList,callList;
    ReentrantLock reentrantLock = new ReentrantLock();
    Toast curToast;
    JSONArray detailJson,typeJson,itemJson,resultJson,callJson,sonDetailJson;
    String curImageFileName ="",curStyleID="";
    ImageView imgv_StlyleImage;
    int selPosition=-1;
    //popwindows
    View contentView;
    PopupWindow popupWindow;
    TextView tv_pop_title;
    LinearLayout templetlisthead;
    ListView lv_Detail,sondetailList;
    JSONArray poJSON,headJSON;
    DrawerLayout drawerLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mate);
        contentView = LayoutInflater.from(this).inflate(R.layout.popselect, null);
        hideBottomUIMenu();
        System.out.println("A");
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo","");
        curLoginUser=paramBundle.getString("LoginUser","");
        curDepartNo=paramBundle.getString("CurDepartNo","");
        curDepart=paramBundle.getString("CurDepart","");
        curServiceUrl=paramBundle.getString("ServiceUrl","");
        curServiceDir=paramBundle.getString("ServiceDir","");
        CPUID=paramBundle.getString("CPUID");
        mainLinerLayout=findViewById(R.id.mainLinerLayout);
        txt_OrderNo=findViewById(R.id.txt_OrderNo);
        txt_StyleNo=findViewById(R.id.txt_StyleNo);
        txt_PO=findViewById(R.id.txt_PO);
        txt_Color=findViewById(R.id.txt_Color);
        txt_ColorNo=findViewById(R.id.txt_ColorNo);
        txt_Size=findViewById(R.id.txt_Size);
        txt_StyleSort=findViewById(R.id.txt_StyleSort);
        txt_PSXX=findViewById(R.id.txt_PSXX);
        txt_HintInfo=findViewById(R.id.txt_HintInfo);
        sonBarcode=findViewById(R.id.sonBarcode);
        sonBarcode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    hideIM(textView);
                    playRingtone();
                    if (edt_barcode.getText().length()==0) {
                        curToast.setText(getString(R.string.PleaseInputBarcode));
                        curToast.show();
                    } else {
                        searchBarcodeData(edt_barcode.getText().toString());
                    }
                }
                return false;
            }
        });
        sondetailList=findViewById(R.id.sondetailList);
        findViewById(R.id.btn_SelectPO).setOnClickListener(this);
        System.out.println("B");
        //抽屉
        drawerLayout = findViewById(R.id.drawer);
        txt_OrderNo.setText(paramBundle.getString("OrderNo",""));
        txt_StyleNo.setText(paramBundle.getString("StyleNo",""));
        txt_StyleSort.setText(paramBundle.getString("StyleSort",""));
        txt_Color.setText(paramBundle.getString("Color",""));
        txt_ColorNo.setText(paramBundle.getString("ColorNo",""));
        txt_Size.setText(paramBundle.getString("Size",""));
        txt_PO.setText(paramBundle.getString("PO",""));
        findViewById(R.id.btn_StorageQuery).setOnClickListener(this);
        System.out.println("C");
        //实例化;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        waitDialog= new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
        edt_barcode=findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        playRingtone();
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            searchBarcodeData(edt_barcode.getText().toString());
                        }
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
        sonBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        playRingtone();
                        System.out.println("sonBarcode:"+sonBarcode.getText().toString());
                        if (sonBarcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            MateQueryBarcode(sonBarcode.getText().toString());
                        }
                        sonBarcode.selectAll();
                    }

                }
                if (event.getKeyCode()== KeyEvent.KEYCODE_ENTER) return true;
                else return false;
            }
        });
        btn_find=findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_editBarcode=findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        edt_checkReal=findViewById(R.id.edt_checkReal);
        findViewById(R.id.btn_Close).setOnClickListener(this);
        imgv_StlyleImage=findViewById(R.id.imgv_StyleImage);
        System.out.println("D");
        findViewById(R.id.view_oneBtn).setOnClickListener(this);
        findViewById(R.id.view_twoBtn).setOnClickListener(this);
        findViewById(R.id.view_threeBtn).setOnClickListener(this);
        findViewById(R.id.view_fourBtn).setOnClickListener(this);
        findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        findViewById(R.id.view_sixBtn).setOnClickListener(this);
        findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        findViewById(R.id.view_eightBtn).setOnClickListener(this);
        findViewById(R.id.view_nineBtn).setOnClickListener(this);
        findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        findViewById(R.id.view_pointBtn).setOnClickListener(this);
        findViewById(R.id.view_delBtn).setOnClickListener(this);
        findViewById(R.id.view_affirmBtn).setOnClickListener(this);
        findViewById(R.id.view_clearBtn).setOnClickListener(this);
        findViewById(R.id.view_QueryBtn).setOnClickListener(this);
        findViewById(R.id.view_NoStorageBtn).setOnClickListener(this);
        //其他功能键
        findViewById(R.id.btn_refreshCall).setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnClickListener(this);
        findViewById(R.id.btn_affirm).setOnClickListener(this);
        itemGrid=findViewById(R.id.itemGrid);
        callList=findViewById(R.id.callList);
        System.out.println("E");
        //表格;
        titleGrid=findViewById(R.id.titleGrid);
        titleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setSelected(true);
                try {
                    GetItem(typeJson.optJSONObject(i).getString("MateType"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        itemGrid=findViewById(R.id.itemGrid);
        System.out.println("F");

        detailList=findViewById(R.id.detailList);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selPosition=position;
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //发消息置焦点
        Message msg =new Message();
        msg.what = msgFocusBarcode;
        mHandler.removeMessages(msg.what);
        mHandler.sendMessage(msg);
        GetType();
        refreshCall();
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {
                        case MSG_SonDetailOver:
                            if (sonDetailJson==null) return;
                            SonDetailAdapter sonDetailAdapter = new SonDetailAdapter(getBaseContext());
                            sondetailList.setAdapter(sonDetailAdapter);
                            break;
                        case msgGetCallListOver:
                            if (callJson==null) return;
                            System.out.println("准备显示：CallList");
                            CallListAdapter callListAdapter = new CallListAdapter(getBaseContext());
                            callList.setAdapter(callListAdapter);
                            break;
                        case msgGetImg:
                            //设置焦点
                            System.out.println(TAG+"获取图片-------------------------------1.Start");
                            if (curImageFileName.length()>0)
                                getImage(curImageFileName, txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                            System.out.println(TAG+"获取图片-------------------------------1.End");
                            break;
                        case MSG_DetailOver:
                            DetailListAdapter detailListAdapter = new DetailListAdapter(getBaseContext());
                            detailList.setAdapter(detailListAdapter);
                            break;
                        case MSG_TypeOver:
                            TypeGridAdapter typeGridAdapter = new TypeGridAdapter(getBaseContext());
                            titleGrid.setAdapter(typeGridAdapter);
                            break;
                        case MSG_ItemOver:
                            ItemGridAdapter itemGridAdapter = new ItemGridAdapter(getBaseContext());
                            itemGrid.setAdapter(itemGridAdapter);
                            break;
                        case MSG_ERRMSG:
                            Bundle bundle1=msg.getData();
                            String mesg=bundle1.getString("MSG","");
                            curToast.setText(mesg);
                            curToast.show();
                        case msgFocusBarcode:
                            setEditBarcodeFocus();
                            break;
                        case msgShowImage:
                            //判断本地是否有图片;
                            String imgfilepath = getCacheDir().toString();
                            File file = new File(imgfilepath + "/" + curImageFileName);
                            //判断图片是否存在，如果不存在则从网络获取;
                            if (file.exists() == true) {
                                Log.d(TAG, "准备从本地取图片显示---------------");
                                //从本地取图片
                                Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                                imgv_StlyleImage.setImageBitmap(bitmap);
                            }
                            break;
                        case MSG_SaveTrans:
                        case MSG_SCANBARCODE:
                            setEditBarcodeFocus();
                            fillFormtext();
                            break;
                        case msgGetPOOver:
                            //准备显示明细
                            SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getApplicationContext());
                            selectTempletListAdapter.selectJSON= poJSON;
                            lv_Detail.setAdapter(selectTempletListAdapter);
                            break;
                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };


    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private JSONArray selectJSON;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectJSON.length())
                    return selectJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.popselect_item, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,dp2px(45)));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJson.length()>0)
        {
            AlertDialog alertDialog;
            try {
                //别的参数刷新
                if (resultJson.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJson.getJSONObject(0).getString("OrderNo"));
                if (resultJson.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJson.getJSONObject(0).getString("StyleNo"));
                if (resultJson.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJson.getJSONObject(0).getString("PO"));
                if (resultJson.getJSONObject(0).has("PSXX")==true) txt_PSXX.setText(resultJson.getJSONObject(0).getString("PSXX"));
                if (resultJson.getJSONObject(0).has("DBH")==true) SelDBH=resultJson.getJSONObject(0).getString("DBH");
                if (resultJson.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJson.getJSONObject(0).getString("Color"));
                if (resultJson.getJSONObject(0).has("ColorNo")==true) txt_ColorNo.setText(resultJson.getJSONObject(0).getString("ColorNo"));
                if (resultJson.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJson.getJSONObject(0).getString("Size"));
                if (resultJson.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(resultJson.getJSONObject(0).getString("StyleSort"));
                if (resultJson.getJSONObject(0).has("LoadDetail")==true) {
                    if (resultJson.getJSONObject(0).getString("LoadDetail").toUpperCase().equals("YES"))
                        GetDetail(PrBarcode,SelDBH);
                } else{
                    detailJson=new JSONArray("[]");
                    DetailListAdapter detailListAdapter = new DetailListAdapter(getBaseContext());
                    detailList.setAdapter(detailListAdapter);
                }
                //刷新明细;
                if (resultJson.getJSONObject(0).has("RefreshCall")==true) {
                    if (resultJson.getJSONObject(0).getString("RefreshCall").toUpperCase().equals("YES")) refreshCall();
                }
                if (resultJson.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJson.getJSONObject(0).getString("HintInfo"));
                if (resultJson.getJSONObject(0).has("ResultInfo")==true) {
                    txt_HintInfo.setText(resultJson.getJSONObject(0).getString("ResultInfo"));
                    alertDialog = new AlertDialog.Builder(this)
                            .setTitle("系统提示").setMessage(resultJson.getJSONObject(0).getString("ResultInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (resultJson.getJSONObject(0).has("ErrInfo")==true)
                {
                    alertDialog = new AlertDialog.Builder(this)
                            .setTitle("系统提示").setMessage(resultJson.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (resultJson.getJSONObject(0).has("ImageFile") == true){
                    curImageFileName =resultJson.getJSONObject(0).getString("ImageFile");
                    //判断本地是否有图片;
                    String imgfilepath = this.getCacheDir().toString();
                    File file = new File(imgfilepath + "/" + curImageFileName);
                    System.out.println("图片文件路径:" + imgfilepath + "/" + curImageFileName);
                    //判断图片是否存在，如果不存在则从网络获取;
                    if (file.exists() == true) {
                        Log.d(TAG, "准备从本地取图片显示---------------");
                        //从本地取图片
                        Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                        imgv_StlyleImage.setImageBitmap(bitmap);
                    } else {
                        Log.d(TAG, "发消息从网络获取图片---------------");
                        Drawable drawable = getResources().getDrawable(R.mipmap.err404);
                        BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
                        imgv_StlyleImage.setImageBitmap(errBitDraw.getBitmap());
                        //发前消息，获取图片;
                        Message msg = new Message();
                        msg.what = msgGetImg;
                        mHandler.removeMessages(msg.what);
                        mHandler.sendMessage(msg);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }



    private void initPopwindow() {;
        popupWindow = new PopupWindow(contentView,-1,-2);
        popupWindow.setFocusable(true);
        contentView.findViewById(R.id.btn_pop_ok).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {

                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        contentView.findViewById(R.id.btn_pop_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        tv_pop_title = (TextView)contentView.findViewById(R.id.tv_pop_title);
        lv_Detail = (ListView)contentView.findViewById(R.id.lv_Detail);
        templetlisthead = (LinearLayout)contentView.findViewById(R.id.templetlisthead);
        popupWindow.setBackgroundDrawable((Drawable)new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
    }

    private void showSelectPO(){
        //先显示对话框,再调用查询加载
        initPopwindow();
        try {
            poJSON =new JSONArray("[]");
            headJSON = new JSONArray("[{\"TitleName\":\"PO\",\"TitleText\":\"PO号\",\"TxtSize\":20,\"TxtWidth\":180,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("请选择配片PO");
        contentView.findViewById(R.id.btn_pop_cancel).setVisibility(View.GONE);
        CreateListHead();
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    txt_PO.setText(poJSON.optJSONObject(postion).getString("PO"));
                    GetDetail(PrBarcode,SelDBH);
                    popupWindow.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        int deviationX=500,deviationY=500;
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
        //加载默认的历史合约;
        SearchPO();
    }


    private void SearchPO() {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_MateGetPO  @OperType='GetPO',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()+ "',@StyleSort='" + txt_StyleSort.getText().toString()
                +"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }


    //创建列;
    private void CreateListHead() {
        System.out.println("CreateListHead()");
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        System.out.println("CreateListHead()"+i);
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(templetlisthead.getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(edt_barcode);
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam)
    {
        if (typeJson==null) GetType();

        String SqlComm = "Exec KeyPoint_MateScan @Barcode='" + BarcodeParam + "',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString() + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + curDepartNo
                + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo +"',@UserName='"+curLoginUser+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        //执行SQL过程
        PrBarcode = BarcodeParam;
    }

    //刷新缸布列表;
    private void MateQueryBarcode(String BarcodeParam)
    {
        String SqlComm = "Exec KeyPoint_MateScan @Barcode='" + BarcodeParam + "',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString() + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + curDepartNo
                + "',@OPERTYPE='MateQuery',@UserNo='" + curLoginUserNo +"',@UserName='"+curLoginUser+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //获取明细数据
    private void GetDetail(String BarcodeParam,String DBHParam) {
        selPosition=-1;
        try {
            detailJson=new JSONArray("[]");
            DetailListAdapter detailListAdapter = new DetailListAdapter(getBaseContext());
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sqlcmd="Exec KeyPoint_MateGetDetail @OperType='Detail',@Barcode='" + BarcodeParam+"',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                +"',@DBH='"+DBHParam
                + "',@Color='" + txt_Color.getText().toString()+ "',@PSXX='" + txt_PSXX.getText().toString() + "',@ColorNo='" + txt_ColorNo.getText().toString()+ "',@Size='" + txt_Size.getText().toString() + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + curDepartNo
                + "',@UserNo='" + curLoginUserNo +"',@UserName='"+curLoginUser+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        ReadSQLData(sqlcmd);
    }

    //获取明细数据
    private void GetItem(String TypeParam) {
        try {
            itemJson=new JSONArray("[]");
            ItemGridAdapter itemGridAdapter = new ItemGridAdapter(getBaseContext());
            itemGrid.setAdapter(itemGridAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sqlcmd="Exec KeyPoint_MateGetItem @OperType='Item',@Type='" + TypeParam +"',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString() + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + curDepartNo
                + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        ReadSQLData(sqlcmd);
    }
    //获取明细数据
    private void GetType() {
        String sqlcmd="Exec KeyPoint_MateGetItem @OperType='Type',@DepartNo='" + curDepartNo
                + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        ReadSQLData(sqlcmd);
    }




    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_mate_listhead, null, false);
            view.setTag(position);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((detailJson.optJSONObject(position).has("SerNo") == true)&&(view.findViewById(R.id.text_view_SerNo)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_SerNo)).setText(detailJson.optJSONObject(position).getString("SerNo"));
                    ((TextView) view.findViewById(R.id.text_view_SerNo)).setTextColor(color);
                }

                if ((detailJson.optJSONObject(position).has("PartName") == true)&&(view.findViewById(R.id.text_view_PartName)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_PartName)).setText(detailJson.optJSONObject(position).getString("PartName"));
                    ((TextView) view.findViewById(R.id.text_view_PartName)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("StorageNum") == true)&&(view.findViewById(R.id.text_view_StorageNum)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_StorageNum)).setText(detailJson.optJSONObject(position).getString("StorageNum"));
                    ((TextView) view.findViewById(R.id.text_view_StorageNum)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("UseNum") == true)&&(view.findViewById(R.id.text_view_UseNum)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_UseNum)).setText(detailJson.optJSONObject(position).getString("UseNum"));
                    ((TextView) view.findViewById(R.id.text_view_UseNum)).setTextColor(getResources().getColor(R.color.text_red));
                }
                if ((detailJson.optJSONObject(position).has("NeedNum") == true)&&(view.findViewById(R.id.text_view_NeedNum)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_NeedNum)).setText(detailJson.optJSONObject(position).getString("NeedNum"));
                    ((TextView) view.findViewById(R.id.text_view_NeedNum)).setTextColor(getResources().getColor(R.color.text_red));
                }
                if ((detailJson.optJSONObject(position).has("MateReason") == true)&&(view.findViewById(R.id.text_view_MateReason)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_MateReason)).setText(detailJson.optJSONObject(position).getString("MateReason"));
                    ((TextView) view.findViewById(R.id.text_view_MateReason)).setTextColor(getResources().getColor(R.color.text_red));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }


    //订单表格适配器;
    public final class CallListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public CallListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return callJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return callJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_mate_callhead, null, false);
            view.setTag(position);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (callJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = callJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((callJson.optJSONObject(position).has("SerNo") == true)&&(view.findViewById(R.id.text_view_SerNo)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_SerNo)).setText(callJson.optJSONObject(position).getString("SerNo"));
                    ((TextView) view.findViewById(R.id.text_view_SerNo)).setTextColor(color);
                }
                if ((callJson.optJSONObject(position).has("CallTime") == true)&&(view.findViewById(R.id.text_view_CallTime)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_CallTime)).setText(callJson.optJSONObject(position).getString("CallTime"));
                    ((TextView) view.findViewById(R.id.text_view_CallTime)).setTextColor(color);
                }
                if ((callJson.optJSONObject(position).has("TransTime") == true)&&(view.findViewById(R.id.text_view_TransTime)!=null)) {
                    ((TextView) view.findViewById(R.id.text_view_TransTime)).setText(callJson.optJSONObject(position).getString("TransTime"));
                    ((TextView) view.findViewById(R.id.text_view_TransTime)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","CallListAdapter_position:"+position);
            return view;
        }
    }


    //订单表格适配器;
    public final class SonDetailAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SonDetailAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return sonDetailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return sonDetailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_mate_sondetailhead, null, false);
            view.setTag(position);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (sonDetailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = sonDetailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if (sonDetailJson.optJSONObject(position).has("OrderNo") == true) {
                    ((TextView) view.findViewById(R.id.text_view_OrderNo)).setText(sonDetailJson.optJSONObject(position).getString("OrderNo"));
                    ((TextView) view.findViewById(R.id.text_view_OrderNo)).setTextColor(color);
                }
                if (sonDetailJson.optJSONObject(position).has("Color") == true) {
                    ((TextView) view.findViewById(R.id.text_view_Color)).setText(sonDetailJson.optJSONObject(position).getString("Color"));
                    ((TextView) view.findViewById(R.id.text_view_Color)).setTextColor(color);
                }
                if (sonDetailJson.optJSONObject(position).has("PartName") == true) {
                    ((TextView) view.findViewById(R.id.text_view_PartName)).setText(sonDetailJson.optJSONObject(position).getString("PartName"));
                    ((TextView) view.findViewById(R.id.text_view_PartName)).setTextColor(color);
                }
                if (sonDetailJson.optJSONObject(position).has("Size") == true) {
                    ((TextView) view.findViewById(R.id.text_view_Size)).setText(sonDetailJson.optJSONObject(position).getString("Size"));
                    ((TextView) view.findViewById(R.id.text_view_Size)).setTextColor(color);
                }
                if (sonDetailJson.optJSONObject(position).has("Number") == true) {
                    ((TextView) view.findViewById(R.id.text_view_Number)).setText(sonDetailJson.optJSONObject(position).getString("Number"));
                    ((TextView) view.findViewById(R.id.text_view_Number)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","sonDetailAdapter_position:"+position);
            return view;
        }
    }
    //订单表格适配器;
    public final class ItemGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ItemGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return itemJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return itemJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_mate_item, null, false);
            view.setTag(position);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (itemJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = itemJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((itemJson.optJSONObject(position).has("MainItem") == true)&&(view.findViewById(R.id.tv_MainItem)!=null)) {
                    ((TextView) view.findViewById(R.id.tv_MainItem)).setText(itemJson.optJSONObject(position).getString("MainItem"));
                    ((TextView) view.findViewById(R.id.tv_MainItem)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ItemGridAdapter_position:"+position);
            return view;
        }
    }


    //订单表格适配器;
    public final class TypeGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public TypeGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return typeJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return typeJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_mate_item, null, false);
            view.setTag(position);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (typeJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = typeJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((typeJson.optJSONObject(position).has("MateType") == true)&&(view.findViewById(R.id.tv_MainItem)!=null)) {
                    ((TextView) view.findViewById(R.id.tv_MainItem)).setText(typeJson.optJSONObject(position).getString("MateType"));
                    ((TextView) view.findViewById(R.id.tv_MainItem)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ItemGridAdapter_position:"+position);
            return view;
        }
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()>=7)){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
                if (StrPenColor.equals("Main") == true)
                    PenColor = getResources().getColor(R.color.text_main);
            }
        }
        return PenColor;
    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        System.out.println(jsonArray);
                        String OPERTYPE="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("SCANBARCODE")||OPERTYPE.toUpperCase().equals("TransCall".toUpperCase())) {
                            resultJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("MateQuery".toUpperCase())){
                            sonDetailJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SonDetailOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("DETAIL")) {
                            detailJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("TYPE")) {
                            typeJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_TypeOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("ITEM")) {
                            itemJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ItemOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("SaveTrans".toUpperCase())) {
                            resultJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SaveTrans;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("GETPO")){
                            Message msg = new Message();
                            poJSON =jsonArray;
                            msg.what = msgGetPOOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("CallList".toUpperCase())){
                            Message msg = new Message();
                            callJson =jsonArray;
                            msg.what = msgGetCallListOver;
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                        }

                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            mHandler.removeMessages(msg.what);
                            mHandler.sendMessage(msg);
                            return;
                        }
                    }else{
                        //显示预排单;
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回任何数据!");
                        msg.setData(bundle);
                        mHandler.removeMessages(msg.what);
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    mHandler.removeMessages(msg.what);
                    mHandler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }
            }

        };
        new Thread(run).start();
    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }


    //获取图片;
    private void getImage(final String paramImageFile,final String paramOrderNo,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = DBUtil.OpenSQL("Exec KeyPoint_GetStyleImg @OrderNo='"+paramOrderNo+"',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, paramImageFile);
                                //发前消息，获取图片;
                                Message msg = new Message();
                                msg.what = msgShowImage;
                                mHandler.removeMessages(msg.what);
                                mHandler.sendMessage(msg);
                                System.out.println(paramImageFile+"图片保存");
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }



    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = this.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        Bundle paramBundle = new Bundle();
        switch (v.getId()) {
            case R.id.btn_StorageQuery:
                drawerLayout.openDrawer(Gravity.RIGHT);
                sonBarcode.setFocusable(true);
                sonBarcode.requestFocus();
                MateQueryBarcode(PrBarcode);
                break;
            case R.id.view_QueryBtn:
                Intent tmpQueryIntent=new Intent(this, QueryActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "配片情况查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","NO");
                tmpQueryIntent.putExtras(paramBundle);
                startActivity(tmpQueryIntent);
                break;
            case R.id.view_NoStorageBtn:
                saveData("NoStorage");
                break;
            case R.id.btn_SelectPO:
                if (txt_OrderNo.getText().toString().length()>0) showSelectPO();
                else{
                    curToast.setText("请先扫描条码!");
                    curToast.show();
                }
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length()>0){
                    searchBarcodeData(edt_barcode.getText().toString());
                } else {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                    return;
                }
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + edt_checkReal.getText().toString().indexOf("."));
                if ((edt_checkReal.getText().toString().indexOf(".") == -1)&&(edt_checkReal.getText().toString().indexOf("/") == -1)) {
                    edt_checkReal.getText().append(".");
                }
                break;
            case R.id.view_clearBtn:
                edt_checkReal.setText("");
                break;
            case R.id.view_affirmBtn:
                //置对应行的内容;
                if(detailList.getCheckedItemPosition()<0){
                    curToast.setText("请先选择需求部位!");
                    curToast.show();
                    return;
                }
                if (edt_checkReal.getText().toString().length()==0){
                    curToast.setText("请输入需求数量!");
                    curToast.show();
                    return;
                }
                detailList.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
                if (detailJson!=null&&detailJson.length()>0){
                    String Type="",Item="";
                    try {
                        if (titleGrid.getCheckedItemPosition()>-1)
                            Type=typeJson.optJSONObject(titleGrid.getCheckedItemPosition()).getString("MateType");
                        if (itemGrid.getCheckedItemPosition()>-1)
                            Item=itemJson.optJSONObject(itemGrid.getCheckedItemPosition()).getString("MainItem");
                        if (Type.length()>0&&(Item.length()>0||itemJson.length()==0)){
                            String MainItem="";
                            if (Item.length()>0) MainItem=Type+"-"+Item;
                            else MainItem=Type;
                            detailJson.optJSONObject(detailList.getCheckedItemPosition()).put("MateReason",MainItem);
                            detailJson.optJSONObject(detailList.getCheckedItemPosition()).put("NeedNum",edt_checkReal.getText().toString());
                            ((BaseAdapter)detailList.getAdapter()).notifyDataSetChanged();
                            edt_checkReal.setText("");
                        } else {
                            curToast.setText("请选择配片原因及配片部件!");
                            curToast.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_Close:
                finish();
                break;
            case R.id.btn_submit:
                saveData("Normal");
                break;
            case R.id.btn_refreshCall:
                refreshCall();
                break;
            case R.id.btn_affirm:
                if (callList.getCheckedItemPosition()>-1) {
                    try {
                        String MateID = callJson.optJSONObject(callList.getCheckedItemPosition()).getString("MateID");
                        String TransTime = callJson.optJSONObject(callList.getCheckedItemPosition()).getString("TransTime");
                        if (TransTime.length()==0){
                            String SqlComm = "Exec KeyPoint_MateCallList @OPERTYPE='TransCall',@MateID='" + MateID
                                    + "',@UserNo='" + curLoginUserNo+ "',@DepartNo='" + curDepartNo+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
                            //调用WebService过程并处理界面更新;
                            ReadSQLData(SqlComm);
                        } else{
                            curToast.setText("已经报到过无需再次报到!");
                            curToast.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else{
                    curToast.setText("请选择要报到的记录!");
                    curToast.show();
                }
                break;
            default:
                break;
        }
    }

    //刷新数据
    private void refreshCall(){
        try {
            callJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CallListAdapter callListAdapter = new CallListAdapter(getBaseContext());
        callList.setAdapter(callListAdapter);
        String SqlComm = "Exec KeyPoint_MateCallList @OPERTYPE='CallList',@UserNo='" + curLoginUserNo
                + "',@DepartNo='" + curDepartNo+ "',@CPUID='" + CPUID + "',@TermNo='"+ MainApplication.TermNo +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //提交所选择的工序至服务器,然后刷新工序列表;
    private void saveData(final String callType){
        if (detailJson == null || detailJson.length()==0) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String MateID = java.util.UUID.randomUUID().toString();
                String PartName="",NeedNum="",MateReason="",StorageNum="0",DBH="",UseNum="0";
                int insertCount=0;
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into SceneMateDe(MateDeID,MateID,PartName,DBH,StorageNum,UseNum,NeedNum,MateReason) values(newid(),?,?,?,?,?,?,?)");
                    //增加明细表
                    PartName="";NeedNum="";MateReason="";
                    for (int i = 0; i < detailJson.length(); i++) {
                        if (detailJson.getJSONObject(i).has("PartName") == true) PartName=detailJson.getJSONObject(i).getString("PartName");
                        if (detailJson.getJSONObject(i).has("DBH") == true) DBH=detailJson.getJSONObject(i).getString("DBH");
                        if (detailJson.getJSONObject(i).has("NeedNum") == true) NeedNum=detailJson.getJSONObject(i).getString("NeedNum");
                        if (detailJson.getJSONObject(i).has("UseNum") == true) UseNum=detailJson.getJSONObject(i).getString("UseNum");
                        if (detailJson.getJSONObject(i).has("StorageNum") == true) StorageNum=detailJson.getJSONObject(i).getString("StorageNum");
                        if (detailJson.getJSONObject(i).has("MateReason") == true) MateReason=detailJson.getJSONObject(i).getString("MateReason");
                        if (NeedNum.length()>0&&MateReason.length()>0&&Integer.parseInt(NeedNum)>0) {
                            insertCount++;
                            pstmt.setString(1, MateID);
                            pstmt.setString(2, PartName);
                            pstmt.setString(3, DBH);
                            pstmt.setString(4, StorageNum);
                            pstmt.setString(5, UseNum);
                            pstmt.setString(6, NeedNum);
                            pstmt.setString(7, MateReason);
                            pstmt.executeUpdate();
                        }
                    }
                    pstmt.close();
                    if (insertCount>0) {
                        //调用存储过程;
                        SqlComm = " Exec KeyPoint_MateSaveTrans @OperType='SaveTrans',@MateID='" + MateID + "',@OrderNo='" + txt_OrderNo.getText().toString()
                                + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                                + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString()
                                + "',@PSXX='" + txt_PSXX.getText().toString() + "',@ColorNo='" + txt_ColorNo.getText().toString()
                                + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + curDepartNo + "',@CallType='" + callType
                                + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@TermNo='" + MainApplication.TermNo + "'";
                        ReadSQLData(SqlComm);
                    } else {
                        curToast.setText("没有需保存的需求信息,请检查！");
                        curToast.show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+ R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }
}
